const express = require('express')
const { json } = require('express/lib/response')
const router = express.Router()

const ShopCart = require('../Schemas/ShopCartSchema')

router.post('/addCart', (req, res) => {
    ShopCart.find({
        $and: [{ userid: req.body.userid }, { skuid: req.body.skuid, }, { color: req.body.color }, {
            version: req.body.version
        }]
    }).then(p => {
        if (p.length == 0) {
            const cart = new ShopCart(req.body)
            cart.save()
            res.json({
                code: 200,
                message: "添加购物车成功"
            })
        } else {
            ShopCart.updateOne({ _id: p[0]._id.toString() }, {
                $set: {
                    buynumber: p[0].buynumber + req.body.buynumber
                }
            }).then(() => {
                res.json({
                    code: 200,
                    message: "添加购物车成功"
                })
            })
        }
    }).catch(err => {
        res.json({
            code: 500,
            message: "添加购物车失败"
        })
    })
})

router.get('/getCart', (req, res) => {
    ShopCart.find({ userid: req.query.userid }).then((carts) => {
        res.json({
            code: 200,
            message: "查询成功",
            carts
        })
    }).catch((err) => {
        res.json({
            code: 500,
            message: "查询失败"
        })
    });
})

router.post('/deleteCart', (req, res) => {
    let cart = req.body.cart
    if (cart.length != 0) {
        cart.forEach(e => {
            ShopCart.deleteOne({ _id: e._id }).then(p => {
                console.log(p);
            })
        });
    }
    res.json({
        code: 200,
        message: "删除成功"
    })

})
router.post('/deleteOne', (req, res) => {
    ShopCart.deleteOne({ _id: req.body._id }).then((p) => {
        res.json({
            code: 200,
            message: '删除成功',
        })
    }).catch((err) => {
        console.log(err);
        res.json({
            code: 500,
            message: '删除失败',
        })
    })
})
module.exports = router